package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("send4Order")
    public Result send4Order(String telephone) {
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        if (code == null) {
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        try {
            SMSUtils.sendSmsCode(telephone,code.toString());
            System.out.println("发送的验证码为:"+code);
        } catch (ClientException e) {
            e.printStackTrace();
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.setex("order_"+telephone,300,code.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            jedis.close();
        }
        return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS,null);
    }

    @RequestMapping("send4Login")
    public Result send4Login(String telephone) {
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        if (code == null) {
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        try {
            SMSUtils.sendSmsCode(telephone,code.toString());
            System.out.println("发送的验证码为:"+code);
        } catch (ClientException e) {
            e.printStackTrace();
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.setex("login_"+telephone,300,code.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            jedis.close();
        }
        return Result.success(MessageConstant.SEND_VALIDATECODE_SUCCESS,null);
    }
}
